package net.zoneland.knowledge.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.lang3.StringUtils;

/**
 * gson工具类.
 * @author bcc
 * @Description: 2019-10-21 10:39
 */
@SuppressWarnings("checkstyle:RegexpSinglelineJava")
public final class GsonUtils {

    /**
     * gson.
     */
    public static final Gson GSON = new GsonBuilder()
        .setLenient()
        .create();

    /**
     * 编码方式.
     */
    public static final String DEFAULT_CHARSET_NAME = "UTF-8";

    private GsonUtils() {
    }

    public static String getStringField(final JsonObject data, final String key) {
        if(data.has(key) && null != data.get(key) && !data.get(key).isJsonNull()) {
            return data.get(key).getAsString();
        }
        return null;
    }

    public static Integer getIntField(final JsonObject data, final String key) {
        if(data.has(key)) {
            if(StringUtils.isNumeric(data.get(key).toString())) {
                return data.get(key).getAsInt();
            }
        }
        return 0;
    }

    private static InputStream getResourceAsStream(final String filename) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
    }

    /**
     * 对象转Json.
     * @Author Pbody
     * @Date 10:51 2020/3/15
     * @Param [obj]
     * @return java.lang.String
     **/
     public static String toJson(final Object obj) {
        if (obj == null) {
            return "{}";
        }
        return GSON.toJson(obj);
    }


}
